#!/bin/bash

# 批量服务启动脚本
# 这是一个便捷的启动脚本，用于快速启动config.yaml中的所有服务

# 获取脚本所在目录
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

# 设置颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

echo -e "${BLUE}======================================${NC}"
echo -e "${BLUE}    ROS 服务批量启动器${NC}"
echo -e "${BLUE}======================================${NC}"

# 检查ROS环境
if [ -z "$ROS_DISTRO" ]; then
    echo -e "${RED}错误：ROS环境未配置！${NC}"
    echo -e "${YELLOW}请先运行：${NC}"
    echo "source /opt/ros/noetic/setup.bash  # 根据你的ROS版本调整"
    echo "source ~/catkin_ws/devel/setup.bash"
    exit 1
fi

echo -e "${GREEN}✓ ROS环境已配置 (ROS $ROS_DISTRO)${NC}"

# 检查roscore是否运行
if ! pgrep -f "roscore\|rosmaster" > /dev/null; then
    echo -e "${YELLOW}警告：roscore似乎没有运行${NC}"
    echo -e "${YELLOW}建议先启动roscore：${NC}"
    echo "roscore &"
    echo ""
    read -p "是否继续？(y/N): " -n 1 -r
    echo
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        echo "已取消启动"
        exit 1
    fi
else
    echo -e "${GREEN}✓ ROS master正在运行${NC}"
fi

# 检查screen是否安装
if ! command -v screen &> /dev/null; then
    echo -e "${RED}错误：screen未安装！${NC}"
    echo -e "${YELLOW}请安装screen：${NC}"
    echo "sudo apt-get install screen"
    exit 1
fi

echo -e "${GREEN}✓ screen已安装${NC}"

# 显示当前运行的服务会话
echo ""
echo -e "${BLUE}检查当前运行的服务会话...${NC}"
python3 "$SCRIPT_DIR/scripts/batch_service_launcher.py" -l

echo ""
echo -e "${BLUE}开始启动所有服务...${NC}"
echo ""

# 启动所有服务
python3 "$SCRIPT_DIR/scripts/batch_service_launcher.py" "$@"

# 检查启动结果
if [ $? -eq 0 ]; then
    echo ""
    echo -e "${GREEN}======================================${NC}"
    echo -e "${GREEN}    所有服务启动完成！${NC}"
    echo -e "${GREEN}======================================${NC}"
    echo ""
    echo -e "${YELLOW}常用命令：${NC}"
    echo "查看所有screen会话: screen -list"
    echo "连接到会话: screen -r service_<服务名>"
    echo "分离会话: Ctrl+A, D"
    echo "终止所有服务: $SCRIPT_DIR/kill_all_services.sh"
    echo "或使用Python脚本: $0 -k"
    echo ""
else
    echo ""
    echo -e "${RED}======================================${NC}"
    echo -e "${RED}    启动过程中出现错误！${NC}"
    echo -e "${RED}======================================${NC}"
    echo ""
    echo -e "${YELLOW}请检查上面的错误信息${NC}"
fi 